import 'dart:async';

import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/opt_input_field.dart';
import 'package:casdon/core/auth/auth_storage.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/modules/device/application/notification/product_category_notifier.dart';
import 'package:casdon/modules/device/ui/screen/tm_bind_account_screen.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

@RoutePage()
class GetBindCatCodeScreen extends ConsumerStatefulWidget {
  final String sessionId;

  const GetBindCatCodeScreen({super.key, required this.sessionId});

  @override
  ConsumerState<GetBindCatCodeScreen> createState() =>
      _GetBindCatCodeScreenState();
}

class _GetBindCatCodeScreenState extends ConsumerState<GetBindCatCodeScreen> {
  final TextEditingController _codeController = TextEditingController();
  Timer? _countdownTimer;
  int _countdownSeconds = 0;
  String? _account;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _initData();
  }

  @override
  void dispose() {
    _codeController.dispose();
    _countdownTimer?.cancel();
    super.dispose();
  }

  Future<void> _initData() async {
    // 获取涂鸦账号
    final authStorage = ref.read(authStorageProvider.notifier);
    String? account = await authStorage.getUserAccount();

    // 处理账号格式：如果包含 "86-"，则去掉前缀
    if (account != null && account.contains('86-')) {
      account = account.substring(3);
    }

    if (mounted) {
      setState(() {
        _account = account;
      });

      // 如果是手机号，发送验证码并开启倒计时
      if (_account != null && _isPhoneNumber(_account!)) {
        await _sendVerificationCode();
      }
    }
  }

  bool _isPhoneNumber(String account) {
    // 简单的手机号验证：11位数字，以1开头
    return RegExp(r'^1[3-9]\d{9}$').hasMatch(account);
  }

  Future<void> _sendVerificationCode() async {
    if (_account == null || !_isPhoneNumber(_account!)) {
      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      final deviceRepository = ref.read(deviceRepositoryProvider);
      final ret = await deviceRepository.sendTMBindVerifyCode(
        sessionId: widget.sessionId,
        phoneNumber: _account!,
      );
      if (ret == null) {
        ToastUtil.show("发送验证码失败");
        if (mounted) {
          setState(() {
            _isLoading = false;
          });
        }
        return;
      }
      try {
        final map = ret;
        final data = map['data'];
        final success = data is Map<String, dynamic>
            ? data['success']
            : map['success'];
        if (success == true) {
          ToastUtil.show("发送验证码成功");
        } else {
          ToastUtil.show(data['message'] ?? "发送验证码失败");
        }
      } catch (_) {
        ToastUtil.show("发送验证码失败");
      }
      // 检查认证返回结果

      if (mounted) {
        _startCountdown();
      }
    } catch (e, st) {
      Log.e('发送验证码失败: $e', e, st);

      ToastUtil.show("发送验证码失败");
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  void _startCountdown() {
    setState(() {
      _countdownSeconds = 60;
    });

    _countdownTimer?.cancel();
    _countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (!mounted) {
        timer.cancel();
        return;
      }

      setState(() {
        if (_countdownSeconds > 0) {
          _countdownSeconds--;
        } else {
          timer.cancel();
        }
      });
    });
  }

  Future<void> _handleCodeCompleted(String code) async {
    if (code.length != 6) {
      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      final deviceRepository = ref.read(deviceRepositoryProvider);
      final ret = await deviceRepository
          .findTMUserListToAuthLoginWithPhoneNumber(
            sessionId: widget.sessionId,
            phoneNumber: _account!,
            code: code,
          );
      final map = ret ?? {};
      final data = map['data'];
      final success =
          (data is Map<String, dynamic> ? data['success'] : null) ??
          map['success'];
      if (success != true) {
        final message =
            (data is Map<String, dynamic> ? data['message'] : null) ??
            map['message'];
        ToastUtil.show(message ?? "获取用户账户列表失败");
        return;
      }

      final container = data is Map<String, dynamic> ? data : map;
      final result = container['result'];
      final list = result is Map<String, dynamic>
          ? result['userListToAuthLogin'] as List<dynamic>?
          : null;
      if (list == null || list.isEmpty) {
        ToastUtil.show("未找到可绑定的账号");
        return;
      }

      final users = list.map((e) {
        final m = e as Map<String, dynamic>;
        return BindUserItem(
          encryptedUserIdentifier:
              m['encryptedUserIdentifier'] as String? ?? '',
          avatar: m['avatar'] as String? ?? '',
          nickname: m['nickname'] as String? ?? '',
          userType: m['userType'] as String? ?? '',
        );
      }).toList();

      if (!mounted) return;
      context.router.replace(
        TMBindAccountRoute(users: users, sessionId: widget.sessionId),
      );
    } catch (e, st) {
      Log.e('验证码验证失败: $e', e, st);
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('验证失败: ${e.toString()}')));
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CommonAppBar(title: '绑定账号', backgroundColor: Colors.white),
      backgroundColor: Colors.white,
      body: SafeArea(
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(height: 32.h),
              // 标题
              Text(
                '输入验证码',
                style: context.textTheme.headlineMedium?.copyWith(
                  fontSize: 35.r,
                  fontWeight: FontWeight.bold,
                ),
              ),
              SizedBox(height: 10.h),
              // 描述文字
              Text(
                '激活语音功能，请先验证并绑定阿里系账号',
                style: context.textTheme.bodySmall?.copyWith(
                  fontSize: 13.r,
                  color: const Color(0xFF828282),
                ),
              ),
              SizedBox(height: 60.h),
              // 验证码输入框
              OTPInputField(
                length: 6,
                controller: _codeController,
                onCompleted: _handleCodeCompleted,
              ),
              SizedBox(height: 20.h),
              // 发送提示和重发按钮
              Row(
                children: [
                  Text(
                    '验证码已发送至您的手机:',
                    style: context.textTheme.bodySmall?.copyWith(
                      fontSize: 13.r,
                      color: const Color(0xFF828282),
                    ),
                  ),
                  SizedBox(width: 5.w),
                  // 重发按钮
                  TextButton(
                    onPressed: _countdownSeconds == 0 && !_isLoading
                        ? _sendVerificationCode
                        : null,
                    style: TextButton.styleFrom(
                      padding: EdgeInsets.symmetric(
                        horizontal: 8.w,
                        vertical: 4.h,
                      ),
                      minimumSize: Size(0, 28.h),
                      tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                    ),
                    child: Text(
                      _countdownSeconds > 0
                          ? '${_account ?? ''}(${_countdownSeconds}s)'
                          : _account ?? '',
                      style: context.textTheme.bodySmall?.copyWith(
                        fontSize: 13.r,
                        color: _countdownSeconds > 0
                            ? const Color(0xFF828282)
                            : const Color(0xFFCDA285),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
